<template>
  <div class="container-image">
    <el-card>
      <div slot="header" class="header">
        <my-bread>素材管理</my-bread>
      </div>
      <!-- 按钮组 -->
      <div class="btn-nav">
        <el-radio-group v-model="reqParams.collect" size="small" @change="changeCollect()">
          <el-radio-button :label="false">全部</el-radio-button>
          <el-radio-button :label="true">收藏</el-radio-button>
        </el-radio-group>
        <el-button style="float:right" @click="dialogVisible = true" type="success" size="small">添加素材</el-button>
      </div>
      <!-- 图片列表 -->
      <div class="img-list">
        <div class="img-item" v-for="item in imageList" :key="item.id">
          <img :src="item.url" alt />
          <div class="img-option">
            <span
              class="el-icon-star-off"
              @click="taggleCollect(item)"
              :class="{red:item.is_collected}"
            ></span>
            <span class="el-icon-delete" @click="delImage(item.id)"></span>
          </div>
        </div>
      </div>
      <!-- 分页 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        hide-on-single-page
        @current-change="changePager"
        :page-size="reqParams.per_page"
        :current-page="reqParams.page"
      ></el-pagination>
    </el-card>
        <!-- 添加图片对话框 -->
    <el-dialog title="添加素材" :visible.sync="dialogVisible" width="30%">
      <el-upload
        class="avatar-uploader"
        action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
        name="image"
        :headers="headers"
        :show-file-list="false"
        :on-success="uploadImageSuccess"
       
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-dialog>
  </div>
</template>
<script>
import auth from '@/utils/auth'
export default {
  name: "image-page",
  data() {
    return {
      total: 0,
      // 控制对话框显示隐藏
      dialogVisible: false,
      // 请求头
      headers:{
        Authorization :`Bearer ${auth.getUser().token}`
      },
      reqParams: {
        //   默认激活全部按钮
        collect: false,
        //   页码
        page: 1,
        // 每页显示的条数
        per_page: 10,
        
      },
      //   图片数据
      imageList: [],
      // 图片地址
      imageUrl:null
    };
  },
  created() {
    this.getImage();
  },
  methods: {
    // 得到图片资源
    async getImage() {
      //   接后得到的对象
      const {
        data: { data }
      } = await this.$http.get("/user/images", { params: this.reqParams });
      // 设置data中图片列表数据
      this.imageList = data.results;
    //  console.log(data.results);
          // 设图片总数
      this.total = data.total_count

     
    },
    changePager(newPage) {
      this.reqParams.page = newPage;
      this.getImage();
    },
    // 部分和收藏进行切换
    changeCollect() {
      this.reqParams.page = 1;
      this.getImage();
    },
    // 收藏/取消图片函数
    async taggleCollect(item) {
      // 结构对象

      try {
        const {
          data: { data }
        } = await this.$http.put(`/user/images/${item.id}`, {
          collect: !item.is_collected
        });
        // 操作成功,修改图片星星状态
        this.$message.success(data.collect ? "添加收藏成功" : "取消收藏成功");
        item.is_collected = !data.collect;
        this.getImage();
      } catch (e) {
        this.$message.error(
          item.is_collected ? "取消收藏失败!!!" : "添加收藏失败!!!"
        );
      }
    },
    // 删除图片
    async delImage(id) {
      // 弹出提示框
      this.$confirm("是否删除???", "友情提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            await this.$http.delete(`/user/images/${id}`);
            this.$message.success("删除成功");
            this.getImage();
          } catch (e) {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          // return alert('未知错误');
        });
    },
    // 上传素材
    uploadImageSuccess (res) {
      this.$message.success('上传成功')
      
      this.imageUrl = res.data.url;
      // 一段时间关闭图片上传对话框
      window.setTimeout(()=>{
        this.dialogVisible = false;
        this.getImage();
      },2000);
      // console.log(this.imageList);
      
      
    }
  }
};
</script>
<style scoped lang="less">
.btn-nav {
  margin-bottom: 20px;
}
.img-list {
  margin-bottom: 20px;
  .img-item {
    width: 180px;
    height: 180px;
    border: 1px dashed #ddd;
    display: inline-block;
    margin-top: 20px;
    margin-right: 60px;
    position: relative;
    img {
      width: 100%;
      height: 100%;
      display: block;
      overflow: hidden;
    }
    .img-option {
      width: 100%;
      height: 30px;
      background: rgba(0, 0, 0, 0.3);
      line-height: 30px;
      position: absolute;
      left: 0;
      bottom: 0;
      text-align: center;
      span {
        color: #fff;
        margin: 0 30px;
        &.red {
          color: red;
        }
      }
    }
  }
}
</style>